package com.sxsihe.heartmate.view;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import com.sxsihe.heartmate.R;
import com.sxsihe.heartmate.util.SharePreferenceUtil;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collections;

public class DrawWaveView extends View {
	private static final String TAG = "DrawWaveView";
	private Path path;
	public Paint paint = null;
	public Paint axisPaint = null;
	public Paint linePaint = null;
	Bitmap cacheBitmap = null;
	Canvas cacheCanvas = null;
	Paint bmpPaint = new Paint();
	private int maxPoint = 0;
	private int currentPoint = 0;
	private int maxValue = 0;
	private int minValue = 0;
	private float x = 0;
	private float y = 0;
	private float prex = 0;
	private float prey = 0;
	private  String x_mark= "";
	
	private int mBottom = 0;
	private int mHeight = 0;
	private int mLeft = 0;
	private int mWidth = 0;



    private ArrayList<Integer> xAxis = new ArrayList();
    private ArrayList<Integer> yAxis = new ArrayList();
    int step = 28;

	private float mPixPerHeight = 0;
	private float mPixPerWidth = 0;
	Canvas mCanvas = null;
	int devStatus = 4;
	SharePreferenceUtil spu ;
	
	public DrawWaveView(Context context){

		super(context);
		if(spu==null){
			spu = SharePreferenceUtil.getInstance(context);
		}
	}

	public DrawWaveView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		if(spu==null){
			spu = SharePreferenceUtil.getInstance(context);
		}

		
	}
	public void setValue(int maxPoint, int maxValue, int minValue){
		this.maxPoint = maxPoint;
		this.maxValue = maxValue;
		this.minValue = minValue;
		

	}
	
	public void updateDensity(){
		if(isReady()){
			mPixPerHeight = (float)mHeight/(maxValue  - minValue);
			mPixPerWidth =  (float)mWidth/maxPoint ;
			clear();
		}
	}
	
	public void initView(){

		mBottom = this.getBottom();
		mWidth = this.getWidth();
		mLeft = this.getLeft();
		mHeight = this.getHeight();
		
		mPixPerHeight = (float)mHeight/(maxValue  - minValue);
		mPixPerWidth =  (float)mWidth/maxPoint ;

		cacheBitmap = Bitmap.createBitmap(mWidth, mHeight, Config.ARGB_8888);
		cacheCanvas = new Canvas();
		path = new Path();
		cacheCanvas.setBitmap(cacheBitmap);
		
		paint = new Paint(Paint.DITHER_FLAG);
        paint.setColor(spu.getColor("color_coordinate"));
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(2);
		paint.setAntiAlias(true);
		paint.setDither(true);



        axisPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        axisPaint.setColor(spu.getColor("color_text"));
        axisPaint.setStrokeWidth(2);
        axisPaint.setTextSize(25);
        axisPaint.setAntiAlias(true);
        axisPaint.setDither(true);


		linePaint = new Paint(Paint.DITHER_FLAG);
		linePaint.setColor(spu.getColor("color_line"));
		linePaint.setStyle(Paint.Style.STROKE);
		linePaint.setStrokeWidth(2);
		linePaint.setAntiAlias(true);
		linePaint.setDither(true);
//		linePaint.setAntiAlias(true);
//		linePaint.setDither(true);

		bmpPaint.setColor(spu.getColor("color_bg"));

        currentPoint =0;
	}
	
	public void clear()
	{
		Paint clearPaint = new Paint();
		clearPaint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
		cacheCanvas.drawPaint(clearPaint);
		clearPaint.setXfermode(new PorterDuffXfermode(Mode.SRC));
		currentPoint =0;
		path.reset();

		invalidate();
	}

	public boolean isReady(){
		return initFlag;
	}
	
	public void updateData(int data){
		y = translateData2Y(data);
		x = translatePoint2X(currentPoint);
		if(currentPoint == 0){
			path.moveTo(x, y);
			currentPoint ++;
			prex = x;
			prey = y;
		}else if(currentPoint == maxPoint){
			cacheCanvas.drawPath(path,paint);
			currentPoint = 0;
		}else{
			path.quadTo(prex,prey,x, y);
			currentPoint ++;
			prex = x;
			prey = y;
		}

		invalidate();
		if(currentPoint == 0){
			clear();
		}
	}
	public void updateData(String str,int data){
		y = translateData2Y(data);
		x = translatePoint2X(currentPoint);
		if(currentPoint == 0){
			x_mark = str;
			path.moveTo(x, y);
			currentPoint ++;
			prex = x;
			prey = y;
		}else if(currentPoint == maxPoint){
			cacheCanvas.drawPath(path,paint);
			currentPoint = 0;
		}else{
			path.quadTo(prex,prey,x, y);
			currentPoint ++;
			prex = x;
			prey = y;
		}

		invalidate();
		if(currentPoint == 0){
			clear();
		}

	}
	/**
	 * y = top + height - (data -minValue) * height/(2*maxValue)
	 * @param data
	 * @return
	 */
	private float translateData2Y(int data){
		return (float)mBottom - (data - minValue) *mPixPerHeight ;
	}
	/**
	 * x = mLeft + mWidth/
	 * @param point
	 * @return
	 */
	private float translatePoint2X(int point){
		return (float)mLeft + point * mPixPerWidth;
	}
	
    private boolean initFlag = false;
	@Override
	protected void onDraw(Canvas canvas) {
		mCanvas = canvas;
		canvas.drawColor(spu.getColor("color_bg"));

		int width = this.getWidth();
		int height = this.getHeight();

		for (int i = width/2; i < width; i += step) {
			if ((i-width/2)  % (step * 5) == 0) {
				paint.setStrokeWidth(3);
                if(!xAxis.contains(i))
                    xAxis.add(i);
            }else {
				paint.setStrokeWidth(1);
			}
			canvas.drawLine(i, 0, i, height, paint);
		}

		for (int i = width/2; i >0; i -= step) {
			if ((width/2-i)  % (step * 5) == 0) {
				paint.setStrokeWidth(3);
                if(!xAxis.contains(i))
                    xAxis.add(i);
            }else {
				paint.setStrokeWidth(1);
			}
            canvas.drawLine(i, 0, i, height, paint);
		}

//		/*1*/
		for (int i = height/2; i < height; i += step) {
			if ((i-height/2) % (step * 5) == 0) {
				paint.setStrokeWidth(3);
                if(!yAxis.contains(i))
                    yAxis.add(i);
			}
			else {
				paint.setStrokeWidth(1);
			}
			canvas.drawLine(0, i, width, i, paint);
		}
//		/*2*/
		for (int i = height/2; i >0 ; i -= step) {
			if ((height/2-i) % (step * 5) == 0) {
				paint.setStrokeWidth(3);
                if(!yAxis.contains(i))
                    yAxis.add(i);
			}
			else {
				paint.setStrokeWidth(1);
			}
			canvas.drawLine(0, i, width, i, paint);
		}

        Collections.sort(xAxis);
        Collections.sort(yAxis);
        int point_x = 0;
        int point_y = yAxis.size()/2;
//        for(int x : xAxis){
//            canvas.drawText(point_x+"", x+15, yAxis.get(yAxis.size()-2)+step+10, axisPaint);
//            point_x+=10;
//        }

        for(int y : yAxis){
            canvas.drawText(point_y+"", xAxis.get(0)-step-10, y+step+10, axisPaint);
            point_y-=1;
        }
		if(!x_mark.equals("")){
			canvas.drawText(x_mark, xAxis.get(xAxis.size()-2), yAxis.get(yAxis.size()-1)+step, axisPaint);
		}

//        canvas.drawText("(s)", xAxis.get(0)+step*3, yAxis.get(yAxis.size()-1)+step*2, axisPaint);
        canvas.drawText("(mV)", 15, yAxis.get(yAxis.size()- 2) -step*2, axisPaint);

		paint.setStrokeWidth(4);

//        canvas.drawBitmap(cacheBitmap, 0, 0, bmpPaint);
		canvas.drawPath(path, linePaint);

        drawDevStatus(canvas);
		super.onDraw(canvas);
		
	}
	@Override
	protected void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		initFlag = false;
		 Log.d(TAG,"onConfigurationChanged");
	}

	// for rotate screen things
	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		 Log.d(TAG,"onAttachedToWindow");
		 initFlag = false;
	}
	// for rotate screen things
	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		// TODO Auto-generated method stub
		super.onLayout(changed, left, top, right, bottom);
		 if(!initFlag){
			 initView();
			 initFlag = true;
		 }
	}

	public void toggleDevStatus(int devStatus) {
		this.devStatus = devStatus ;
		invalidate();
	}

	public void drawDevStatus(Canvas canvas){
//		Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dev_status_not_found);
		/*switch (devStatus) {

			case TGDevice.STATE_CONNECTING:
				bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dev_status_connecting);
				break;
			case TGDevice.STATE_CONNECTED:
				bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dev_status_connected);
				break;
			case TGDevice.STATE_NOT_FOUND:
				bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dev_status_not_found);
				break;
			case TGDevice.STATE_DISCONNECTED:
				bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dev_status_disconnect);
				break;
		}*/

//		canvas.drawBitmap(bmp, 30, this.getHeight() - bmp.getHeight() - 30, paint);

	}


}
